package com.example.resource;

import com.example.model.UserDto;
import com.example.model.UserFormDataDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jboss.resteasy.reactive.multipart.FileUpload;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
@Path("/start/post")
public class PostExampleResource {

    @Inject
    ObjectMapper objectMapper;

    @POST
    @Path("/body")
    public UserDto body(@Valid UserDto userDto) throws JsonProcessingException {
        String jsonString = objectMapper.writeValueAsString(userDto);
        log.info("UserDto: {}", jsonString);

        userDto.setVersion(999);
        return userDto;
    }

    /**
     * 接收表单请求
     * @param userFormDataDto 表单请求参数对象
     * @return 返回响应结果
     * @throws JsonProcessingException json序列化异常
     */
    @POST
    @Produces(MediaType.APPLICATION_FORM_URLENCODED)
    @Path("/form")
    public String form(@BeanParam UserFormDataDto userFormDataDto) throws JsonProcessingException {
        String jsonString = objectMapper.writeValueAsString(userFormDataDto);
        log.info("UserFormDataDto: {}", jsonString);
        return "Hello from RESTEasy Reactive, form param = " + jsonString;
    }

    @POST
    @Path("/upload")
    public String upload(@FormParam("file") FileUpload fileUpload) throws IOException {
        String fileName = fileUpload.fileName();

        java.nio.file.Path path = fileUpload.uploadedFile();
        File file = path.toFile();
        String content = FileUtils.readFileToString(file, Charset.defaultCharset());

        log.info("fileName: {}", fileName);
        log.info("fileContent: {}", content);
        return "4";
    }
}
